<?php
use think\facade\Cache;

/**
 * Here is your custom functions.
 */
function return_json($code,$msg,$ary=array()){
	$data = array(
		'code' => $code,
		'msg' => $msg,
		'data' => $ary
	);
	return json($data);
}

function url($str='',$ary = []){
	if($str != ''){
		$url = '';
		if(!empty($ary)){
			foreach ($ary as $k=>$val){
				if ($val != null)
				{
					$url .= $k .'=' . urlencode(mb_convert_encoding($val, 'utf-8', 'auto')) . '&';
				}
			}
		}
		if($url != ''){
			$url = '/' . $str . '?' . $url;
		}else{
			$url = '/' . $str;
		}		
		$strs = rtrim($url, '&');
	}else{
		$strs = request()->fullUrl();
	}
	return $strs;
}

if (!function_exists('cache')) {
    /**
     * 设置缓存
     * @param $key
     * @param string $value
     * @param null $expires 过期时间
     * @return bool|mixed
     */
    function cache($key, $value = "", $expires = null)
    {
        if (empty($value)) {
            $cache = Cache::get($key);
        } else {
            if (empty($expires)) {
                $cache = Cache::set($key, $value);
            } else {
                $cache = Cache::set($key, $value, $expires);
            }
        }
        return $cache;
    }
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

/**
 * 实现存储全局变量
 * 调用 cacheStatic('my_key', 'my value')
 * 读取 cacheStatic('my_key')
 */
function cacheStatic($key, $value = null)
{
    static $cache = [];
    if ($value === null) {
        return $cache[$key] ?? null;
    }
    $cache[$key] = $value;
}

//时间戳转换为时间 输出格式为 Y-m-d
function rtdate($val){
	$strtime="";
	if($val=="" || $val==0){
		$strtime="";
	}else{
		$strtime=date("Y-m-d",$val);
	}
	return $strtime;
}

//时间戳转换为时间 输出格式为 Y-m-d H:i:s
function rttime($field){
	$strtime="";
	if($field=="" || $field==0){
		$strtime="";
	}else{
		$strtime=date("Y-m-d H:i:s",$field);
	}
	return $strtime;
}

//将年 月 日时间转化为时间戳
function timestamp($val){
	return strtotime($val);
}

//距今 天
function toDates($time_stamp){
	$time = time() - $time_stamp;
	$day = 24 * 60 * 60;
	return round($time/$day,1);
}

//随机数0~9
//例：randomkeys(4) 生成四位随机数字
function randomkeys($length){
	$key = "";
	for($i=0;$i<$length;$i++){
		$key .= mt_rand(0,9);
	}
	return $key;
}

//将字符串分割成一维数组
//例:str_explode(',',$str);
function str_explode($epx,$string){
	$ary = array();
	$ary = explode($epx,$string);
	return $ary;
}

//将一维数组转换为字符串
//例:ary_to_str(',',$ary);
function ary_to_str($epx,$ary=array()){
	$str = implode($epx,$ary);
	return $str;
}

//二维数组降一维
function ary_getwhere_out($field,$ary = array()){
    $tmp = array();
    $tmp = array_column($ary, $field);
    return $tmp;
}
//一维数组去重复
function a_array_unique($ary = array()){
    $out = array();
	$out = array_keys(array_flip($ary));
    return $out;
}
//二维数组指定字段排序
function ary_field_sort($array,$field,$sort){
	
	$columnAry = array_column($array, $field);
	if(strtolower($sort)=='desc'){
		array_multisort($columnAry, SORT_DESC, $array);
	}else{
		array_multisort($columnAry, SORT_ASC, $array);
	}
	
    return $array;
}

//字符串截取
function str_sub($str,$s,$e){
	return substr($str,$s,$e);
}

//字符串填充
function strPad($str,$s,$e){
	return str_pad($str,$s,$e);
}

//字符串脱敏
function sensitive($str,$s,$e){
	$len = strlen($str) - $e;
	
	$newstr = '';
	$newstr = str_sub($str,0,$s);
	$newstr = strPad($newstr,$len,'*');
	$newstr = $newstr . str_sub($str,$e*-1,$e);
	return $newstr;
}

//日志-自定义文件名
function setCustom($name,$content){
	$fileName = $name.'_'.date('Y-m-d').'.txt';		//日志文件
	$catalogue = './log/log';						//日志公共目录
	mkdirs($catalogue);								//判断文件夹是否存在不存在则创建
	
	$ary = explode("_",$name);						//字符串按下划线分割成数组
	if(count($ary)>1){
		$folder = $ary[0];
		$filePath = $catalogue.'/'.$folder;			//日志类别目录
		mkdirs($filePath);							//判断文件夹是否存在不存在则创建
		
		$subset = $ary[1];
		$filePath = $filePath.'/'.$subset;
		mkdirs($filePath);
	}else{
		$arr = preg_split("/(?=[A-Z])/",$name);		//字符串按大写字母分隔成数组
		if(count($arr)>1){
			$folder = strtolower($arr[0]);
			$filePath = $catalogue.'/'.$folder;			//日志类别目录
			mkdirs($filePath);							//判断文件夹是否存在不存在则创建
			
			$subset = strtolower($arr[1]);
			$filePath = $filePath.'/'.$subset;
			mkdirs($filePath);
		}else{
			$folder = 'public';
			$filePath = $catalogue.'/'.$folder;			//日志类别目录
			mkdirs($filePath);							//判断文件夹是否存在不存在则创建
		}
	}
	
    $fileUrl = $filePath.'/'.$fileName;				//完整路径
	
    $Ts = fopen($fileUrl,"a+");
    fputs($Ts,"\r\n"."执行日期：".date('Y-m-d H:i:s',time()).  ' ' . "\n" .$content."\n");
    fclose($Ts);
}
//判断文件夹是否存在不存在则创建
function mkdirs($dir, $mode = 0777){
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}
function setLogHour($name,$content){
	$ary = explode("_",$name);
	if(count($ary)>1){
		$folder = $ary[0];
	}else{
		$folder = 'public';
	}
	
    $fileName = $name.'_'.date('Y-m-d_H').'.txt';	//日志文件
	$catalogue = './log/log';						//日志公共目录
	mkdirs($catalogue);
	$filePath = $catalogue.'/'.$folder;				//日志类别目录
	mkdirs($filePath);
    $fileUrl = $filePath.'/'.$fileName;				//完整路径
	
    $Ts = fopen($fileUrl,"a+");
    fputs($Ts,"\r\n"."执行日期：".date('Y-m-d H:i:s',time()).  ' ' . "\n" .$content."\n");
    fclose($Ts);
}

//mysql文件内容
function myScandir($FilePath='./',$Order=0){
    $FilePath = opendir($FilePath);
    while (false !== ($filename = readdir($FilePath))) {
        $FileAndFolderAyy[] = $filename;
    }
    $Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
    return $FileAndFolderAyy;
}

